package cn.school.controller.student;

import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.student.service.ExamListService;
import cn.school.student.service.ExamResultInfoService;
import cn.school.student.service.StudentInfoService;
import cn.school.student.vo.*;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@RestController
@Api(tags = "exam => 考试列表")
@RequestMapping("/exam/list")
public class ExamListController {

    @Resource
    private ExamListService examListService;

    @Resource
    private ExamResultInfoService examResultInfoService;

    @Resource
    private StudentInfoService studentInfoService;

    @ApiModelProperty("分页查询列表")
    @PostMapping("/pageList")
    public CommonResult<CommonPage<ExamListVO>> findExamListPageList(@RequestBody ExamListVO vo){
        IPage<ExamListVO> pageList = examListService.findExamInfoPageList(vo);
        return CommonResult.success(CommonPage.restPage(pageList));
    }

    @ApiOperation("根据ID删除考试信息")
    @PostMapping("/delete")
//    @PreAuthorize("@ss.hasPermi('exam:info:delete')")
    public CommonResult<CommonPage<ExamListVO>> deleteExamInfoById(@RequestBody ExamListVO examListVO){
        int num = examListService.deleteExamListById(String.valueOf(examListVO.getId()));
        if(num>0) return CommonResult.success();
        return CommonResult.failed();
    }

    @ApiOperation("新增or修改考试信息")
    @PostMapping("/edit")
//    @PreAuthorize("@ss.hasPermi('exam:info:edit')")
    public CommonResult<CommonPage<ExamListVO>> addOrUpdateExamInfo(@RequestBody ExamListVO examListVO){
        int num = examListService.addOrUpdateExamList(examListVO);
        if(num>0) return CommonResult.success();
        return CommonResult.failed();
    }

    @ApiOperation("考试成绩录入")
    @PostMapping("/addExamResult")
    public CommonResult<String> addExamResult(@RequestBody ResultTableVO vo){
        return examListService.addExamResult(vo) ? CommonResult.success() : CommonResult.failed("成绩录入失败！");
    }

    @ApiOperation("考试成绩修改")
    @PostMapping("/updateExamResult")
    public CommonResult<String> updateExamResult(@RequestBody ResultTableVO vo){
        return examListService.updateExamResult(vo) ? CommonResult.success() : CommonResult.failed("成绩录入失败！");
    }

    @ApiOperation("考试成绩表导出")
    @PostMapping("/export")
    public void exportExcel(@RequestBody ResultTableVO vo, HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook =  new HSSFWorkbook();
        //创建一个表
        HSSFSheet sheet = workbook.createSheet("学生成绩表");
        //第一行 (表名)
        int rowCount = 0;                     //第 rowCount 行
        HSSFRow row =null;
        row = sheet.createRow(rowCount++);
        row.setHeight((short)(26.5 * 20));
        row.createCell(0).setCellValue("学生成绩");
        //第一行合并
        List<SubjectVO> subjList = vo.getStudentWithSubjectVOList().get(0).getSubjList();
        CellRangeAddress rowRegion = new CellRangeAddress(0,0,0,subjList.size());
        sheet.addMergedRegion(rowRegion);    //进行合并
        //学科
        row =sheet.createRow(rowCount++);
        row.setHeight((short)(22.5*20));
        int column = 0;                      //第 column 列
        row.createCell(column++).setCellValue("学号");
        row.createCell(column++).setCellValue("姓名");
        for (SubjectVO subjectVO : subjList) {
            row.createCell(column++).setCellValue(subjectVO.getSubjName());//给单元格进行赋值
        }
        //成绩
        List<StudentWithSubjectVO> studentWithSubjectVOList = vo.getStudentWithSubjectVOList();//学生考试信息
        for (StudentWithSubjectVO studentWithSubjectVO : studentWithSubjectVOList) {
            column = 0;
            row = sheet.createRow(rowCount++);
            row.createCell(column++).setCellValue(studentWithSubjectVO.getStudentId());
            row.createCell(column++).setCellValue(studentWithSubjectVO.getName());
            List<SubjectVO> subjectVOList = studentWithSubjectVO.getSubjList();//得到考试科目
            for (SubjectVO subjectVO : subjectVOList) {
                row.createCell(column++).setCellValue(subjectVO.getScore());
            }
        }
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        OutputStream os = response.getOutputStream();
        response.setHeader("Content-disposition","attachment;filename=学生成绩表.xls");
        workbook.write(os);
        os.flush();
        os.close();
    }

    @ApiOperation("考试成绩导入")
    @PostMapping("/import")
    @CrossOrigin
    public CommonResult<String> importExcel(@RequestParam("file") MultipartFile file,@RequestParam("vo") String vo) throws Exception {
        ResultTableVO resultTableVO = JSON.parseObject(vo,ResultTableVO.class);
        return examListService.importExcel(file,resultTableVO) ? CommonResult.success() : CommonResult.failed("导入失败");
    }

    @ApiOperation("查询学生成绩")
    @GetMapping("/searchResult/{examId}")
    public CommonResult<ResultTableVO> searchResult(@PathVariable String examId){
        return CommonResult.success(examListService.searchResult(examId));
    }

    @ApiOperation(("根据学生ID查成绩"))
    @GetMapping("/searchResultById/{userId}")
    public CommonResult<List<ExamVO>> searchResultById(@PathVariable String userId){
        return CommonResult.success(examListService.searchResultById(userId));
    }
}
